package com.bringspring.system.permission.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.extra.pinyin.engine.pinyin4j.Pinyin4jEngine;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.annotation.JsbosTask;
import com.bringspring.common.base.*;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.util.*;
import com.bringspring.common.util.treeutil.ListToTreeUtil;
import com.bringspring.system.external.service.SynPushToThirdQyService;
import com.bringspring.system.message.service.SynThirdDingTalkService;
import com.bringspring.system.permission.constant.PermissionConst;
import com.bringspring.system.permission.entity.OrganizeEntity;
import com.bringspring.system.permission.entity.PositionEntity;
import com.bringspring.system.permission.exception.PermissionException;
import com.bringspring.system.permission.mapper.OrganizeMapper;
import com.bringspring.system.permission.model.authorize.AuthorizeConditionModel;
import com.bringspring.system.permission.model.organize.OrganizePagination;
import com.bringspring.system.permission.service.*;
import com.github.pagehelper.util.StringUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import static com.bringspring.system.external.constant.WxCpSysConfigConsts.SYS_DELETE;

/**
 * 组织机构
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Service
public class OrganizeServiceImpl extends ServiceImpl<OrganizeMapper, OrganizeEntity> implements OrganizeService {

    private final static Logger logger = LoggerFactory.getLogger("sync-hr-organize");
    @Autowired
    private PositionService positionService;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private SynPushToThirdQyService synPushToThirdQyService;
    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private Executor threadPoolExecutor;

    @Autowired
    private AuthorizeService authorizeService;


    @Autowired
    private OrganizeMapper organizeMapper;


    @Override
    public List<OrganizeEntity> getList() {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        return this.list(queryWrapper);
    }


    /**
     * 组织列表
     * @param idAll 组织id集合
     * @param keyWord 关键字过滤名称
     * @return
     */
    @Override
    public List<OrganizeEntity> getListAll(List<String> idAll, String keyWord) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(keyWord)) {
            flag = true;
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, keyWord).or().like(OrganizeEntity::getEnCode, keyWord));
        }
        // 排序
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(OrganizeEntity::getLastModifyTime);
        }
        if (idAll.size() > 0) {
            queryWrapper.lambda().in(OrganizeEntity::getId, idAll);
        }

        return this.list(queryWrapper);
    }

    /**
     * 查询所有公司列表
     * 默认条件 category为 company
     * @return
     */
    @Override
    public List<OrganizeEntity> getAllCompanyList(String keyWord) {
        List<OrganizeEntity> data = this.getList(keyWord);
        List<OrganizeEntity> list = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data, data), OrganizeEntity.class);
        list = list.stream().filter(t -> PermissionConst.COMPANY.equals(t.getCategory())).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<OrganizeEntity> getOrganizeByDataPermission(OrganizePagination organizePagination){
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        //按照数据权限查询数据
        if (!userProvider.get().getIsAdministrator()) {
            Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapper, organizePagination.getMenuId(), "base_organize"));
            if (ObjectUtil.isEmpty(companyAuth)) {
                return new ArrayList<>();
            } else {
                queryWrapper = (QueryWrapper<OrganizeEntity>) companyAuth;
            }
        }
        //查询
        queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, EnabledMarkEnum.ENABLE.getCode())
                .select(OrganizeEntity::getId,OrganizeEntity::getParentId, OrganizeEntity::getFullName,OrganizeEntity::getShortName, OrganizeEntity::getEnCode);

        if(StringUtils.isNotEmpty(organizePagination.getType())){
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, organizePagination.getType());
        }
        queryWrapper.lambda()
                .orderByDesc(OrganizeEntity::getSortCode)
                .orderByDesc(OrganizeEntity::getCreatorTime);

        //先通过数据权限查到当前用户组织
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getAllCompanyDataPermission(OrganizePagination organizePagination) {
        UserInfo userInfo = userProvider.get();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        //按照数据权限查询数据
        if(!userInfo.getIsAdministrator()){
            if (Objects.nonNull(organizePagination.getMenuId())){
                if (!userProvider.get().getIsAdministrator()) {
                    Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapper, organizePagination.getMenuId(), "base_organize"));
                    if (ObjectUtil.isEmpty(companyAuth)) {
                        return new ArrayList<>();
                    } else {
                        queryWrapper = (QueryWrapper<OrganizeEntity>) companyAuth;
                    }
                }
            }
        }
        if (StringUtil.isNotEmpty(organizePagination.getKeyword())) {
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, organizePagination.getKeyword()).or().like(OrganizeEntity::getFullName, organizePagination.getKeyword().toLowerCase()));
        }
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.COMPANY);
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> list = this.list(queryWrapper);
        Set<OrganizeEntity> entityList = new HashSet<>(16);
        if (StringUtil.isNotEmpty(organizePagination.getKeyword())) {
            getParentOrganize(list, entityList);
            list.clear();
            list.addAll(entityList);
        }
        return list;
    }

    @Override
    public List<OrganizeEntity> getCompanyList(String modelId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        //按照数据权限查询数据
        if (!userProvider.get().getIsAdministrator()) {
            Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapper, modelId, "base_organize"));
            if (ObjectUtil.isEmpty(companyAuth)) {
                return new ArrayList<>();
            } else {
                queryWrapper = (QueryWrapper<OrganizeEntity>) companyAuth;
            }
        }

        queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName, OrganizeEntity::getEnCode);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.COMPANY)
                .orderByDesc(OrganizeEntity::getSortCode)
                .orderByDesc(OrganizeEntity::getCreatorTime);

        //先通过数据权限查到当前用户组织
        return this.list(queryWrapper);
    }
    /**
     * 根据所属部门id查询[直属公司]
     * @param id 所属组织/部门id
     * @return
     */
    @Override
    public OrganizeEntity getDirectlyUnderCompanyById(String id) {
        OrganizeEntity info = this.getInfo(id);
        if (StringUtils.isNull(info) || StringUtils.isEmpty(info.getOrganizeIdTree())) {
            log.error("获取组织树出错: id=" + id);
            log.error(info == null ? String.valueOf(info):info.toString());
            return null;
        }
        String[] split = info.getOrganizeIdTree().split(",");
        List<String> list = Arrays.asList(split);
        List<OrganizeEntity> orgEntityList = this.getOrgEntityList(list, false);
        Optional<OrganizeEntity> max = orgEntityList.stream().filter(t -> PermissionConst.COMPANY.equals(t.getCategory())).max((e1, e2) -> e1.getOrganizeIdTree().compareTo(e2.getOrganizeIdTree()));
        OrganizeEntity directlyOrg = new OrganizeEntity();
        if (!ObjectUtil.isEmpty(max)) {
            directlyOrg = orgEntityList.stream().filter(t -> PermissionConst.COMPANY.equals(t.getCategory())).max((e1, e2) -> e1.getOrganizeIdTree().compareTo(e2.getOrganizeIdTree())).get();
        }
        return directlyOrg;
    }


    @Override
    public List<OrganizeEntity> getParentIdList(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, "department");
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list;
    }


    @Override
    public List<OrganizeEntity> getParentIdListAsc(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, "department");
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getEnCode).orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public List<OrganizeEntity> getListAscByManagerId(String managerId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getManagerId, managerId);
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getEnCode).orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list;
    }



    @Override
    public List<OrganizeEntity> getListById(Boolean enable) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (enable) {
            queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, EnabledMarkEnum.ENABLE.getCode());
        }
        return this.list(queryWrapper);
    }

    @Override
    public OrganizeEntity getIdListByFullName(String fullName) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getList(String keyword) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, keyword).or().like(OrganizeEntity::getFullName, keyword.toLowerCase()));
        }
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.COMPANY);
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> list = this.list(queryWrapper);
        Set<OrganizeEntity> entityList = new HashSet<>(16);
        if (StringUtil.isNotEmpty(keyword)) {
            getParentOrganize(list, entityList);
            list.clear();
            list.addAll(entityList);
        }
        return list;
    }

    /**
     * 获取父级集合
     *
     * @param list       需要遍历的集合
     * @param entityList 结果集
     */
    private void getParentOrganize(List<OrganizeEntity> list, Set<OrganizeEntity> entityList) {
        List<OrganizeEntity> list1 = new ArrayList<>(16);
        for (OrganizeEntity entity : list) {
            entityList.add(entity);
            OrganizeEntity info = getInfo(entity.getParentId());
            if (Objects.nonNull(info)) {
                list1.add(info);
                if (StringUtil.isNotEmpty(info.getParentId()) && !"-1".equals(info.getParentId())) {
                    getParentOrganize(list1, entityList);
                } else if (StringUtil.isNotEmpty(info.getParentId()) && "-1".equals(info.getParentId())) {
                    entityList.add(info);
                }
            }
        }
    }

    @Override
    public List<OrganizeEntity> getOrgEntityList(List<String> idList, Boolean enable) {
        if (idList.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            if (enable) {
                queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, EnabledMarkEnum.ENABLE.getCode());
            }
            queryWrapper.lambda().in(OrganizeEntity::getId, idList);
//            queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName);
            return this.list(queryWrapper);
        }
        return new ArrayList<>();
    }

    @Override
    public List<OrganizeEntity> getOrgEntityList(Set<String> idList) {
        if (idList.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(OrganizeEntity::getId, OrganizeEntity::getFullName).in(OrganizeEntity::getId, idList);
            List<OrganizeEntity> list = this.list(queryWrapper);
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public List<OrganizeEntity> getOrgListCodeNull() {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().and(q -> q.isNull(OrganizeEntity::getEnCode).or().eq(OrganizeEntity::getEnCode, ""));
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public List<OrganizeEntity> getOrgRedisList() {
        if (redisUtil.exists(cacheKeyUtil.getOrganizeList())) {
            return JsonUtil.getJsonToList(redisUtil.getString(cacheKeyUtil.getOrganizeList()).toString(), OrganizeEntity.class);
        }
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, EnabledMarkEnum.ENABLE.getCode());

        List<OrganizeEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            redisUtil.insert(cacheKeyUtil.getOrganizeList(), JsonUtil.getObjectToString(list), 300);
        }
        return list;
    }

    @Override
    public OrganizeEntity getInfo(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getOrganizeListDataPermission(String menuId) {
        UserInfo userInfo = userProvider.get();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if(!userInfo.getIsAdministrator()){
            //按照数据权限查询数据
            if (Objects.nonNull(menuId)){
                if (!userProvider.get().getIsAdministrator()) {
                    Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapper,menuId, "base_organize"));
                    if (ObjectUtil.isEmpty(companyAuth)) {
                        return new ArrayList<>();
                    } else {
                        queryWrapper = (QueryWrapper<OrganizeEntity>) companyAuth;
                    }
                }
            }
        }
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
        queryWrapper.lambda().eq(OrganizeEntity::getEnabledMark, EnabledMarkEnum.ENABLE.getCode());
        List<OrganizeEntity> list = this.list(queryWrapper);
        if(!userInfo.getIsAdministrator()) {
            //        添加父节点 直属组织
            if (!userProvider.get().getIsAdministrator()) {
                for (int i = 0; i < list.size(); i++) {
                    OrganizeEntity organizeEntity = list.get(i);
                    if (organizeEntity.getParentId().equals("-1")||organizeEntity.getParentId().equals("0")) {
                        continue; // 跳过本次循环  -1是顶级节点，没有父节点
                    }
                    if (Objects.nonNull(list.get(i))) {
                        QueryWrapper<OrganizeEntity> queryWrapperOne = new QueryWrapper<>();
                        queryWrapperOne.lambda().eq(OrganizeEntity::getId, list.get(i).getParentId());
                        OrganizeEntity organize = organizeMapper.selectOne(queryWrapperOne);
                        list.add(organize);
                    }
                }
                //去重
                Set<OrganizeEntity> entityList = new HashSet<>(list);
                list.clear();
                list.addAll(entityList);
            }
        }
        return list;
    }

    @Override
    public List<OrganizeEntity> getListDepartmentDataPermission(String id,String menuId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        //按照数据权限查询数据
        if (!userProvider.get().getIsAdministrator()) {
            Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapper, menuId, "base_organize"));
            if (ObjectUtil.isEmpty(companyAuth)) {
                return new ArrayList<>();
            } else {
                queryWrapper = (QueryWrapper<OrganizeEntity>) companyAuth;
            }
        }
        queryWrapper.lambda().eq(OrganizeEntity::getCategory, "department");
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> list = this.list(queryWrapper);
        //添加父节点
        if (!userProvider.get().getIsAdministrator()) {
            for (int i=0;i<list.size();i++){
                if (list.get(i).getParentId().equals("-1")){
                    continue; // 跳过本次循环
                }
                if (Objects.nonNull(list.get(i))){
                    QueryWrapper<OrganizeEntity> queryWrapperOne = new QueryWrapper<>();
                    queryWrapperOne.lambda().eq(OrganizeEntity::getId,list.get(i).getParentId());
                    OrganizeEntity organize = organizeMapper.selectOne(queryWrapperOne);
                    list.add(organize);
                }
            }
//        去重
            Set<OrganizeEntity> entityList = new HashSet<>(list);
            list.clear();
            list.addAll(entityList);
        }
//        创建一个新的集合
        List<OrganizeEntity> newOrganize = new ArrayList<>();
        for (OrganizeEntity  organizeEntity:list){
            if (organizeEntity.getParentId().equals(id)){
                newOrganize.add(organizeEntity);
            }
        }
        return newOrganize;
    }

    @Override
    public List<OrganizeEntity> getListAllJurisdiction(List<String> idAll, Pagination pagination) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pagination.getKeyword())) {
            flag = true;
            queryWrapper.lambda().and(t -> t.like(OrganizeEntity::getFullName, pagination.getKeyword()).or().like(OrganizeEntity::getEnCode, pagination.getKeyword()));
        }
        // 排序
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
        if (flag) {
            queryWrapper.lambda().orderByDesc(OrganizeEntity::getLastModifyTime);
        }
        if (idAll.size() > 0) {
            queryWrapper.lambda().in(OrganizeEntity::getId, idAll);
        }
//        当没有子层，返回空
        if (idAll.size() == 0){
            queryWrapper.lambda().eq(OrganizeEntity::getFullName,"");
        }
        Page<OrganizeEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<OrganizeEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(),page.getTotal());
    }



    @Override
    public OrganizeEntity getCompanyListById(String id) {
        OrganizeEntity info = this.getInfo(id);
        String[] split = info.getOrganizeIdTree().split(",");
        List<String> list = Arrays.asList(split);
        List<OrganizeEntity> orgEntityList = this.getOrgEntityList(list, false);
        OrganizeEntity directlyOrg = orgEntityList.stream().filter(t -> PermissionConst.COMPANY.equals(t.getCategory()))
                .max((e1, e2) -> e1.getOrganizeIdTree().compareTo(e2.getOrganizeIdTree()))
                .get();
        return directlyOrg;
    }

    /**
     * 获取父级组织id Tree
     * 例如：1,2,3
     *
     * @param entity
     * @return
     */
    @Override
    public String getOrganizeIdTreeALL(OrganizeEntity entity) {
        List<String> list = new ArrayList<>();
        this.getOrganizeIdTree(entity.getParentId(), list);
        // 倒叙排放
        Collections.reverse(list);
        StringBuffer organizeIdTree = new StringBuffer();
        for (String organizeParentId : list) {
            organizeIdTree.append("," + organizeParentId);
        }
        organizeIdTree.append("," + entity.getId());

        String organizeParentIdTree = organizeIdTree.toString();
        if (StringUtils.isNotEmpty(organizeParentIdTree)) {
            organizeParentIdTree = organizeParentIdTree.replaceFirst(",", "");
        }
        return organizeParentIdTree;
    }

    /**
     * 获取第一个组织id
     *
     * @param entity
     * @return
     */
    @Override
    public String getOrganizeIds(OrganizeEntity entity) {
        List<String> list = new ArrayList<>();
        this.getCompanyId(entity.getParentId(), list);
        // 倒叙排放
        Collections.reverse(list);
        StringBuffer organizeIdTree = new StringBuffer();
        String organizeParentIdTree = organizeIdTree.toString();
        if (StringUtils.isNotEmpty(list)) {
            organizeParentIdTree = list.get(list.size() - 1);
        }
        return organizeParentIdTree;
    }

    @Override
    public void getOrganizeId(String organizeId, List<OrganizeEntity> organizeList) {
        OrganizeEntity entity = getInfo(organizeId);
        if (entity != null) {
            organizeList.add(entity);
            if (StringUtils.isNotEmpty(entity.getParentId())) {
                getOrganizeId(entity.getParentId(), organizeList);
            }
        }
    }

    @Override
    public OrganizeEntity getByFullName(String fullName) {
        OrganizeEntity organizeEntity = new OrganizeEntity();
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        List<OrganizeEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            organizeEntity = list.get(0);
        }
        return organizeEntity;
    }

    @Override
    public boolean isExistByFullName(OrganizeEntity entity, boolean isCheck, boolean isFilter) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, entity.getFullName());
        if (!isCheck) {
            if (isFilter) {
                queryWrapper.lambda().ne(OrganizeEntity::getId, entity.getId());
            }
            List<OrganizeEntity> entityList = this.list(queryWrapper);
            if (entityList.size() > 0) {
                for (OrganizeEntity organizeEntity : entityList) {
                    System.out.println(organizeEntity.getFullName());
                    if (organizeEntity != null && organizeEntity.getParentId().equals(entity.getParentId()) && organizeEntity.getCategory().equals(entity.getCategory())) {
                        return true;
                    }
                }
            }
            return false;
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public void getOrganizeIdTree(String organizeId, List<String> organizeParentIdList) {
        OrganizeEntity entity = getInfo(organizeId);
        if (entity != null) {
            organizeParentIdList.add(entity.getId());
            if (StringUtils.isNotEmpty(entity.getParentId())) {
                getOrganizeIdTree(entity.getParentId(), organizeParentIdList);
            }
        }
    }

    @Override
    public void getCompanyId(String organizeId, List<String> organizeParentIdList) {
        OrganizeEntity entity = getInfo(organizeId);
        if (entity != null) {
            if (PermissionConst.COMPANY.equals(entity.getCategory())) {
                organizeParentIdList.add(entity.getId());
            }
            if (StringUtils.isNotEmpty(entity.getParentId())) {
                getCompanyId(entity.getParentId(), organizeParentIdList);
            }
        }
    }

    @Override
    public boolean isExistByEnCode(String enCode, String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getEnCode, enCode);
        if (!StringUtils.isEmpty(id)) {
            queryWrapper.lambda().ne(OrganizeEntity::getId, id);
        }
        return this.count(queryWrapper) > 0;
    }

    @Override
    public void create(OrganizeEntity entity) throws PermissionException {
        //判断同一个父级下是否含有同一个名称
//        if (this.isExistByFullName(entity, false, false)) {
//            throw new PermissionException("名称不能重复");
//        }

        entity.setEnCode(entity.getId());

        if (StringUtils.isEmpty(entity.getId())) {
            entity.setId(RandomUtil.uuId());
        }
        // 通过组织id获取父级组织
        String organizeIdTree = this.getOrganizeIdTreeALL(entity);
        entity.setOrganizeIdTree(organizeIdTree);
        // 设置直属组织
        entity.setOrganizeId(this.getOrganizeIds(entity));
        this.save(entity);
        UserInfo userInfo = userProvider.get();
        threadPoolExecutor.execute(() -> {
            try {
                //创建部门后判断是否需要同步到企业微信
                synPushToThirdQyService.createDepartmentSysToQy(userInfo, false, entity, "");
                //创建部门后判断是否需要同步到钉钉
//                synThirdDingTalkService.createDepartmentSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("创建部门后同步第三方失败，异常：" + e.getMessage());
            }
        });
    }

    @Override
    public void batchSaveOrUpdateBatch(List<OrganizeEntity> entity) {

        this.saveOrUpdateBatch(entity);
    }

    @Override
    public boolean update(String id, OrganizeEntity entity) {
        entity.setId(id);
        // 拼上当前组织id
        String organizeIdTree = this.getOrganizeIdTreeALL(entity);
        entity.setOrganizeIdTree(organizeIdTree);
        // 判断父级是否变化
        OrganizeEntity info = getInfo(id);
        boolean updateById = this.updateById(entity);
        if (info != null && !entity.getParentId().equals(info.getParentId())) {
            // 子集和父级都需要修改父级树
            this.update(entity, info.getCategory());
        }


        UserInfo userInfo = userProvider.get();
        threadPoolExecutor.execute(() -> {
            try {
                //修改组织后判断是否需要同步到企业微信
                synPushToThirdQyService.updateDepartmentSysToQy(userInfo, false, entity, "");
                //修改组织后判断是否需要同步到钉钉
//                synThirdDingTalkService.updateDepartmentSysToDing(false, organizeService.getInfo(id), "");
            } catch (Exception e) {
                log.error("修改组织后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        return updateById;
    }

    @Override
    public void update(OrganizeEntity entity, String category) {
        // 查询子级
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, entity.getId());
        if (PermissionConst.COMPANY.equals(category)) {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, PermissionConst.COMPANY);
        } else {
            queryWrapper.lambda().eq(OrganizeEntity::getCategory, "department");
        }
        List<OrganizeEntity> list = this.list(queryWrapper);
        // 递归修改子组织的父级id字段
        for (OrganizeEntity organizeEntity : list) {
            String organizeIdTree = this.getOrganizeIdTreeALL(entity);
            organizeEntity.setOrganizeIdTree(organizeIdTree);
            this.updateById(organizeEntity);
        }
    }

    @Override
    public ActionResult<String> delete(String orgId) {
        return this.delete(orgId, null);
    }
    @Override
    public ActionResult<String> delete(String orgId, String actionType) {
        String flag = this.allowDelete(orgId);
        if (flag == null) {
            OrganizeEntity organizeEntity = this.getInfo(orgId);
            if (organizeEntity != null) {
                this.removeById(orgId);
                if (StringUtils.isEmpty(actionType) || actionType.equals(SYS_DELETE)) {
                    // 操作类型为空或系统删除，执行第三方同步。
                    UserInfo userInfo = userProvider.get();
                    threadPoolExecutor.execute(() -> {
                        try {
                            //删除部门后判断是否需要同步到企业微信
                            synPushToThirdQyService.deleteDepartmentSysToQy(userInfo, false, orgId, "");
                            //删除部门后判断是否需要同步到钉钉
//                        synThirdDingTalkService.deleteDepartmentSysToDing(false, orgId, "");
                        } catch (Exception e) {
                            log.error("删除部门后同步失败，异常：" + e.getMessage());
                        }
                    });
                }
                return ActionResult.success(MsgCode.SU003.get());
            }
            return ActionResult.fail(MsgCode.FA003.get());
        } else {
            return ActionResult.fail("此记录与\"" + flag + "\"关联引用，不允许被删除");
        }
    }

    @Override
    @DSTransactional
    public boolean first(String id) {
        boolean isOk = false;
        //获取要上移的那条数据的信息
        OrganizeEntity upEntity = this.getById(id);
        Long upSortCode = upEntity.getSortCode() == null ? 0 : upEntity.getSortCode();
        //查询上几条记录
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().lt(OrganizeEntity::getSortCode, upSortCode).eq(OrganizeEntity::getParentId,
                upEntity.getParentId()).orderByDesc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> downEntity = this.list(queryWrapper);
        if (downEntity.size() > 0) {
            //交换两条记录的sort值
            Long temp = upEntity.getSortCode();
            upEntity.setSortCode(downEntity.get(0).getSortCode());
            downEntity.get(0).setSortCode(temp);
            this.updateById(downEntity.get(0));
            this.updateById(upEntity);
            isOk = true;
        }
        return isOk;
    }

    @Override
    @DSTransactional
    public boolean next(String id) {
        boolean isOk = false;
        //获取要下移的那条数据的信息
        OrganizeEntity downEntity = this.getById(id);
        Long upSortCode = downEntity.getSortCode() == null ? 0 : downEntity.getSortCode();
        //查询下几条记录
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().gt(OrganizeEntity::getSortCode, upSortCode).eq(OrganizeEntity::getParentId, downEntity.getParentId()).orderByDesc(OrganizeEntity::getSortCode);
        List<OrganizeEntity> upEntity = this.list(queryWrapper);
        if (upEntity.size() > 0) {
            //交换两条记录的sort值
            Long temp = downEntity.getSortCode();
            downEntity.setSortCode(upEntity.get(0).getSortCode());
            upEntity.get(0).setSortCode(temp);
            this.updateById(upEntity.get(0));
            this.updateById(downEntity);
            isOk = true;
        }
        return isOk;
    }

    @Override
    public String allowDelete(String orgId) {
        // 组织底下是否有组织
        List<OrganizeEntity> list = getListByParentId(orgId);
        if (Objects.nonNull(list) && list.size() > 0) {
            return "组织";
        }
        // 组织底下是否有岗位
        List<PositionEntity> list1 = positionService.getListByOrganizeId(orgId);
        if (Objects.nonNull(list1) && list1.size() > 0) {
            return "岗位";
        }
        // 组织底下是否有用户
        if (userRelationService.existByObjectId(orgId,PermissionConst.ORGANIZE)) {
            return "用户";
        }
        // 组织底下是否有角色
        if (organizeRelationService.existByObjTypeAndOrgId( orgId,PermissionConst.ROLE)) {
            return "角色";
        }
        return null;
    }

    @Override
    public List<OrganizeEntity> getOrganizeName(List<String> id) {
        List<OrganizeEntity> list = new ArrayList<>();
        if (id.size() > 0) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(OrganizeEntity::getId, id);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<OrganizeEntity> getOrganizeNameSort(List<String> id) {
        List<OrganizeEntity> list = new ArrayList<>();
        List<String> organizeTree = id.stream().distinct().collect(Collectors.toList());
        for (String orgId : organizeTree) {
            QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(OrganizeEntity::getId, orgId);
            queryWrapper.lambda().select(OrganizeEntity::getFullName);
            OrganizeEntity entity = this.getOne(queryWrapper);
            if (entity != null) {
                list.add(entity);
            }
        }
        return list;
    }

    @Override
    public List<String> getOrganize(String organizeParentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, organizeParentId);
        queryWrapper.lambda().select(OrganizeEntity::getId);
        List<String> list = this.list(queryWrapper).stream().map(t -> t.getId()).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<String> getOrganizeByOraParentId(String organizeParentId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, organizeParentId);
        List<OrganizeEntity> list = this.list(queryWrapper);
        return list.stream().map(t -> t.getId()).collect(Collectors.toList());
    }

    @Override
    public List<String> getUnderOrganizations(String organizeId) {
        List<String> totalIds = new ArrayList<>();
        this.getOrganizations(organizeId, this.getList(), totalIds);
        return totalIds;
    }

    @Override
    public List<OrganizeEntity> getListByFullName(String fullName) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getFullName, fullName);
        return this.list(queryWrapper);
    }

    @Override
    public List<OrganizeEntity> getListByParentId(String id) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
        return this.list(queryWrapper);
    }

    /**
     * 递归获取子组织
     *
     * @param organizeId
     * @param allIdList
     * @param totalIds
     */
    private void getOrganizations(String organizeId, List<OrganizeEntity> allIdList, List<String> totalIds) {
        List<String> organizations = allIdList.stream().filter(org ->org.getParentId().equals(organizeId)).map(organize -> organize.getId()).collect(Collectors.toList());
        if (organizations.size() > 0) {
            totalIds.addAll(organizations);
            for (String id : organizations) {
                this.getOrganizations(id, allIdList, totalIds);
            }
        }
    }

    @Override
    public List<OrganizeEntity> getAllOrgByUserId(String userId) {
        List<String> ids = new ArrayList<>();
        userRelationService.getAllOrgRelationByUserId(userId).forEach(r -> {
            ids.add(r.getObjectId());
        });
        return this.listByIds(ids);
    }

    @Override
    public String getFullNameByOrgIdTree(String orgIdTree, String regex) {
        String fullName = "";
        if (StringUtils.isNotEmpty(orgIdTree)) {
            String[] split = orgIdTree.split(",");
            StringBuilder orgName = new StringBuilder();
            for (String orgId : split) {
                OrganizeEntity entity = this.getInfo(orgId);
                if (entity != null) {
                    orgName.append(regex).append(entity.getFullName());
                }
            }
            if (orgName.length() > 0) {
                fullName = orgName.toString().replaceFirst(regex, "");
            }
        }
        return fullName;
    }

    @Override
    public List<OrganizeEntity> getListLikeOrgIdTree(String orgId) {
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(OrganizeEntity::getOrganizeIdTree, orgId);
        queryWrapper.lambda().orderByDesc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

}
